<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Http\Requests\AuthorizationsRequest;
use App\Models\User;
use Exception;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Response;
use Illuminate\Support\Facades\Hash;

class AuthorizationsController extends Controller
{
    const TOKEN_TYPE = 'Bearer';

    /**
     * @param AuthorizationsRequest $request
     * @return JsonResponse
     */
    public function store(AuthorizationsRequest $request)
    {
//        $pri = file_get_contents(base_path('cert/alipay/appSecretCert.crt'));
//        $str = chunk_split(base64_encode($pri),64,"\n");
//
//        var_dump("-----BEGIN RSA PRIVATE KEY-----\n$str-----END RSA PRIVATE KEY-----\n");die;




        try {
            $user = User::query()->where('phone', $request->get('phone'))->first();
            if (!$user) {
                return failReturn('手机号不存在');
            }
            if ($request->get('type') == 'password') {
                //密码登录
                if (!Hash::check($request->get('password'), $user->password)) {
                    return failReturn('密码错误');
                }
            } else {
                //短信验证码登录
                if (!checkLoginSms($request->get('phone'), $request->get('code'), 'login')) {
                    return failReturn('验证码错误');
                }
            }
            $user->last_login = now();
            $user->save();
            $token = auth('api')->login($user);
            return $this->responseWithToken($token);
        } catch (Exception $exception) {
            return failReturn($exception->getMessage());
        }

    }

    /**
     * 登录状态检测
     * @return JsonResponse
     */
    public function check()
    {
        return auth('api')->user() ? successReturn() : failReturn('Login expired, please log in again', Response::HTTP_NOT_ACCEPTABLE);
    }

    //刷新token
    public function update()
    {
        $token = auth('api')->refresh();
        return $this->responseWithToken($token);
    }


    //退出登录
    public function destroy()
    {
        auth('api')->logout();
        return successReturn();
    }


    public function responseWithToken($token)
    {
        return successReturn([
            'access_token' => $token,
            'token_type' => self::TOKEN_TYPE,
            'expires_in' => auth('api')->factory()->getTTL() * 60
        ]);
    }
}
